package com.chinasoft.utils;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.*;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import java.util.Map;

public class DbUtils {
    private static DataSource ds = new ComboPooledDataSource("jdbc/mysql");
    static QueryRunner qr = new QueryRunner(ds);

    public static Connection getConn() throws SQLException {
        return ds.getConnection();
    }

    public static DataSource getDataSource() throws SQLException {
        return ds;
    }

    public static int update(String sql, Object... params) {
        int count = 0;
        try {
            count = qr.update(sql, params);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    public static int getCount(String sql, Object... params) {
        int count = 0;
        Object obj=null;
        try {
            obj = qr.query(sql, params, new ScalarHandler());
            count=Integer.parseInt(obj.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return count;
    }

    public static int getId(String sql, Object... params) {
        int id = 0;
        Object obj=null;
        try {
            obj = qr.insert(sql, new ScalarHandler(), params);
            id=Integer.parseInt(obj.toString());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return id;
    }

    public static Object getObject(String sql, Class type, Object... params) {
        Object obj = null;
        try {
            obj = qr.query(sql, params, new BeanHandler<>(type));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return obj;
    }

    public static <T> List<T> getObjects(String sql, Class<T> type, Object... params) {
        List list = null;
        try {
            list = qr.query(sql, params, new BeanListHandler<>(type));
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    public static Map getMap(String sql, Object... params) {
        Map map = null;
        try {
            map = qr.query(sql, params, new MapHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return map;
    }

    public static <T> List<T> getMaps(String sql, Object... params) {
        List list = null;
        try {
            list = qr.query(sql, params, new MapListHandler());
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }
}
